<template>
  <div>
    <h3>登录页面</h3>
    <el-form :model="ruleUser" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="width:500px;margin: 0 auto
    ;">
      <el-form-item label="用户名" prop="username">
        <el-input  v-model="ruleUser.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleUser.password" autocomplete="off"></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </el-form-item>
</el-form>
  </div>
</template>

<script>
import axios from 'axios'
  export default {
    data() {
      var validateUsername = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        } 
        const userRules=/^[a-zA-Z][A-Za-z0-9]{4,15}$/
        if(userRules.test(value)){
          return callback()
        }else{
          callback(new Error('用户名格式不正确'));
        }
      };
      
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } 
        const userRules=/^[a-zA-Z][A-Za-z0-9]{4,16}$/
        if(userRules.test(value)){
          return callback()
        }else{
          callback(new Error('密码格式不正确'));
        }
      };

      return {
        ruleUser: {
          username:'',
          password: '',
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
         
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post('http://127.0.0.1:8000/users/login/',this.ruleUser)
            .then(resp=>{
              console.log(resp);
              if(resp.data.code ==200){
                alert('登录成功')
                this.$store.commit('setUser',resp.data.user)
                let user_json=JSON.stringify(resp.data.user)
                localStorage.getItem('user',user_json)
                localStorage.getItem('token',resp.data.token)
                this.$router.push('/index')
              }
            })
            .catch(err=>{
              console.log(err);
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style>

</style>